package com.tanhua.sso.service;

import com.tanhua.sso.pojo.User;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.util.Map;

@Service
public class UsersService {

    @Autowired
    private UserService userService;

    @Autowired
    private SmsService smsService;

    @Autowired
    private RedisTemplate<String, String> redisTemplate;

    public boolean sendVerificationCode(String token) {
        User user = userService.queryUserByToken(token);
        Map<String, Object> sendCheckCode = smsService.sendCheckCode(user.getMobile());
        int code = ((Integer) sendCheckCode.get("code")).intValue();
        return code == 3;
    }

    public Boolean checkVerificationCode(String code, String token) {
        User user = userService.queryUserByToken(token);
        if (user == null) {
            return false;
        }
        String key = "CHECK_CODE_" + user.getMobile();
        String redisCode = redisTemplate.opsForValue().get(key);
        if (StringUtils.equals(code, redisCode)) {
            redisTemplate.delete(key);
            return true;
        }
        return null;
    }

    public boolean savePhone(String token, String newPhone) {
        User user = userService.queryUserByToken(token);
        if (user == null) return false;
        user.setMobile(newPhone);
        return userService.savaPhone(user);
    }
}
